package com.hsp.core.controller;

import com.hsp.core.constant.BaseApiCode;
import com.hsp.core.pojo.BasePoJo;
import com.hsp.core.service.BaseService;
import com.hsp.core.web.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author 褐发蓝眼的猫
 * @Date 2019/3/15 19:45
 * @Description 基础控制封装，封装基本增删改查，扩展时继承即可
 **/
public abstract class BaseController<BS extends BaseService<T, PK>, T extends BasePoJo, PK>
{
    @Autowired
    private BS serviceImpl;


    @RequestMapping(value = "list")
    @ResponseBody
    protected ApiResult list(@RequestParam("pageNum")int pageNum,
                             @RequestParam("pageSize")int pageSize)
    {
        if(pageNum <= 0) pageNum = 1;
        List<T> list = serviceImpl.listAll(pageNum, pageSize);
        return ApiResult.of(BaseApiCode.SUCCESS, list);

    }

    @RequestMapping(value = "/add")
    @ResponseBody
    protected ApiResult add(@ModelAttribute("obj")T obj)
    {
        serviceImpl.save(obj);
        return ApiResult.of(BaseApiCode.SUCCESS, obj);
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    protected ApiResult delete(@RequestParam("id")PK id)
    {
        serviceImpl.delete(id);
        return ApiResult.of(BaseApiCode.SUCCESS, id);
    }

    @RequestMapping(value = "/detail")
    @ResponseBody
    protected ApiResult detail(@RequestParam("id")PK id)
    {
        T obj = serviceImpl.selectByPrimaryKey(id);
        return ApiResult.of(BaseApiCode.SUCCESS, obj);
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    protected ApiResult update(@ModelAttribute("obj")T obj)
    {
        serviceImpl.updateByPrimaryKeySelective(obj);
        return ApiResult.of(BaseApiCode.SUCCESS, obj);
    }


}
